package com.evangelion.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;

import com.evangelion.core.bean.Usuario;
import com.evangelion.core.bean.UsuarioReporte;
import com.evangelion.core.service.UsuarioReporteService;
import com.evangelion.core.serviceImpl.UsuarioReporteServiceImpl;
import com.evangelion.jasper.ReportReader;
import com.evangelion.jasper.ReportWriter;
import com.evangelion.jasper.domain.Element;
import com.evangelion.jasper.domain.Report;

import com.evangelion.web.filter.SecurityUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import net.sf.jasperreports.engine.JRElement;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.design.JRDesignBand;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;


/**
 * Date: 2/13/14
 */

@WebServlet(name = "reportEditor",
        urlPatterns = {"/reportEditor"}
)
public class ReportServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    @Autowired
    private UsuarioReporteService service;
    
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
    }
      
    /**
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public ReportServlet() {
        super();
    }


    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        get(request, response);
    }


    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String reportName = request.getParameter("reportName");
        String reportConfig = request.getParameter("reportConfig");

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        
        Usuario usuario = SecurityUtils.getUserFromSession(request);

        UsuarioReporte usuarioReporte = service.findUsuarioReporte(usuario, reportName);
        if (null == usuarioReporte) {
            usuarioReporte = new UsuarioReporte();
            usuarioReporte.setUsuario(usuario);
            usuarioReporte.setNameReporte(reportName);
            usuarioReporte.setReporteConfiguracion(reportConfig);
        }
        else {
            Map<String, Element> cMap = new HashMap<String, Element>();

            Gson gson = new Gson();
            Element[] changedElements = gson.fromJson(usuarioReporte.getReporteConfiguracion(), Element[].class);
            for (Element e : changedElements) {
                cMap.put(e.getKey(), e);
            }

            gson = new Gson();
            Element[] justChangedElements = gson.fromJson(reportConfig, Element[].class);
            for (Element e : justChangedElements) {
                cMap.put(e.getKey(), e);
            }
            gson = new Gson();
            String config = gson.toJson(cMap.values());
            usuarioReporte.setReporteConfiguracion(config);
            
            service.save(usuarioReporte);
            
            // leer el fichero JRXML
            String filename = "/general/reportes/";
            ServletContext context = this.getServletContext();
            String pathname = context.getRealPath(filename);

            ReportWriter aReport = new ReportWriter();
            aReport.writeReport(pathname,reportName,cMap);
        }

        JsonObject myObj = new JsonObject();
        myObj.addProperty("success", true);
        
        out.println(myObj.toString());
 
        out.close();
        
    }



    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
     */
    protected void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String reportName = request.getParameter("reportName");
        System.out.println("report is 2 : " + reportName);

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //response.setContentType("application/json");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        try {

            Map<String, Element> cMap = new HashMap<String, Element>();

            Usuario user = SecurityUtils.getUserFromSession(request.getSession());
            UsuarioReporte ur = service.findUsuarioReporte(user, reportName);

            if (null != ur) {
                Gson gson = new Gson();
                Element[] changedElements = gson.fromJson(ur.getReporteConfiguracion(), Element[].class);
                for (Element e : changedElements) {
                    System.out.println(e.toString());
                    cMap.put(e.getKey(), e);
                }
            }

            String filename = "/general/reportes/" + reportName + ".jasper";
            ServletContext context = this.getServletContext();
            String pathname = context.getRealPath(filename);

            Report report = ReportReader.getReport(pathname, cMap);

            Gson gson = new Gson();
            String json = gson.toJson(report);
            out.print(json);
            System.out.println(json);
        }
        catch (JRException e) {
            e.printStackTrace();
        }

        out.flush();
    }
}

